package com.ruyuan.seckilling.render.async.listener;

import com.ruyuan.seckilling.render.async.BaseRenderPageListener;
import com.ruyuan.seckilling.render.async.PageRenderContext;
import com.ruyuan.seckilling.render.async.event.Event05UploadStaticPage;
import com.ruyuan.seckilling.render.service.FileService;
import com.ruyuan.starter.async.anno.Channel;
import com.ruyuan.starter.async.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.ruyuan.seckilling.common.ChannelKey.*;
import static com.ruyuan.seckilling.render.async.PageRenderEventHolder.EVENT_06;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
@Channel(CHANNEL_05_UPLOAD_STATIC_PAGE)
public class Event05Listener extends BaseRenderPageListener<Event05UploadStaticPage> {

    @Autowired
    private FileService fileService;

    @Override
    public boolean accept(BaseEvent event) {
        return event instanceof Event05UploadStaticPage;
    }

    /**
     *  5、上传渲染好了静态页面
     */
    @Override
    protected void doThisStep(Event05UploadStaticPage event, PageRenderContext context) {

        Runnable task = () -> {
            String setStaticPageId = fileService.upload(context.getStaticPageContent());
            if (setStaticPageId == null) {
                context.getPageLog().setSuccess(false);
                context.getPageLog().setInfo("上传html文件出现问题");
                context.setShouldSkip(true);
                return;
            }
            context.setStaticPageId(setStaticPageId);
            context.getPageLog().setStaticPageId(setStaticPageId);
            context.getPageLog().setCompletionTime(System.currentTimeMillis());
            log.info("第5步，上传渲染好了静态页面，url={}", setStaticPageId);
            bossEventBus.publish(CHANNEL_06_SAVE_PAGE_LOG_MESSAGE, EVENT_06, context);
        };

        executorService.execute(CHANNEL_05_UPLOAD_STATIC_PAGE, task);
    }
}
